<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小充电桩物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82882996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\piles;

use think\App;
use app\controller\property\Base;
use app\validate\piles\PilesBasicValidate;
use app\common\repositories\piles\PilesLogRepository;
use app\common\repositories\piles\PilesPlanRepository;
use app\common\repositories\piles\PilesBasicRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;

class PilesBasic extends Base
{

    protected $repository;

    public function __construct(App $app, PilesBasicRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
        $this->assign([
            'addAuth' => property_auth('propertyPilesBasicAdd'),
            'editAuth' => property_auth('propertyPilesBasicEdit'),
            'delAuth' => property_auth('propertyPilesBasicDel'),
            'detailAuth' => property_auth('propertyPilesBasicDetail'),
            'stopAuth' => property_auth('propertyPilesBasicStopCharge'),
            'startAuth' => property_auth('propertyPilesBasicStartCharge'),
        ]);
    }

    /**
     * 充电桩列表
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-05-05 08:02
     */
    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'property_id' => '',
                'plan_id' => '',
                'keywords' => ''
            ]);
            [$page, $limit] = $this->getPage();
            $data = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }
        /** @var PropertyBasicRepository $propertyBasicRepository */
        $propertyBasicRepository = app()->make(PropertyBasicRepository::class);
        $propertyData = $propertyBasicRepository->getPropertyData($this->request->propertyId, ['is_show' => 1]);
        return $this->fetch('piles/basic/list', [
            'propertyData' => $propertyData,
        ]);
    }


    /**
     * 添加充电桩
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-30 10:48
     */
    public function add()
    {
        if ($this->request->isAjax() && $this->request->isGet() && $this->request->param('get_type') == 'planData') {
            $propertyId = $this->request->param('property_id');
            /** @var PilesPlanRepository $planRepository */
            $planRepository = app()->make(PilesPlanRepository::class);
            $planData = $planRepository->getSearch([])
                ->where('property_id', $propertyId)
                ->field('id,plan_name')
                ->select()->toArray();
            return json()->data(['code' => 0, 'data' => $planData]);
        } else if ($this->request->isPost()) {
            $param = $this->request->param([
                'property_id' => '',
                'plan_id' => '',
                'piles_name' => '',
                'port_num' => '',
                'sim_key' => '',
                'piles_type' => '',
                'out_type' => '',
                'address' => '',
                'longitude' => '',
                'latitude' => '',
                'remark' => '',
            ]);
            validate(PilesBasicValidate::class)->scene('add')->check($param);
            if ($this->repository->fieldExists('sim_key', $param['sim_key'])) {
                return $this->error('二维码编号' . $param['sim_key'] . '已存在');
            }
            try {
                $res = $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加充电桩失败', $e);
                return $this->error('网络失败');
            }
        } else {
            /** @var PropertyBasicRepository $propertyBasicRepository */
            $propertyBasicRepository = app()->make(PropertyBasicRepository::class);
            $propertyData = $propertyBasicRepository->getPropertyData($this->request->propertyId, ['is_show' => 1]);
            return $this->fetch('piles/basic/add', [
                'propertyData' => $propertyData,
            ]);
        }
    }

    /**
     * 编辑充电桩
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-30 10:48
     */
    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isAjax() && $this->request->isGet() && $this->request->param('get_type') == 'planData') {
            $propertyId = $this->request->param('property_id');
            /** @var PilesPlanRepository $planRepository */
            $planRepository = app()->make(PilesPlanRepository::class);
            $planData = $planRepository->getSearch([])
                ->where('property_id', $propertyId)
                ->field('id,plan_name')
                ->select()->toArray();
            return json()->data(['code' => 0, 'data' => $planData]);
        } else if ($this->request->isPost()) {
            $param = $this->request->param([
                'property_id' => '',
                'plan_id' => '',
                'piles_name' => '',
                'port_num' => '',
                'sim_key' => '',
                'power_rate' => '',
                'piles_type' => '',
                'out_type' => '',
                'address' => '',
                'longitude' => '',
                'latitude' => '',
                'remark' => '',
            ]);
            if ($this->repository->propertyFieldExists($this->request->propertyId, 'sim_key', $param['sim_key'], $id)) {
                return $this->error('二维码编号' . $param['sim_key'] . '已存在');
            }
            if ($this->repository->propertyFieldExists($this->request->propertyId, 'piles_name', $param['piles_name'], $id)) {
                return $this->error($param['piles_name'] . '已存在');
            }
            validate(PilesBasicValidate::class)->scene('edit')->check($param);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('编辑充电桩失败', $e);
                return $this->error('网络错误');
            }
        } else {
            /** @var PropertyBasicRepository $propertyBasicRepository */
            $propertyBasicRepository = app()->make(PropertyBasicRepository::class);
            $propertyData = $propertyBasicRepository->getPropertyData($this->request->propertyId, ['is_show' => 1]);
            return $this->fetch('piles/basic/edit', [
                'info' => $info,
                'propertyData' => $propertyData,
            ]);
        }
    }

    /**
     * 充电桩详情
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-30 19:09
     */
    public function detail()
    {
        $billId = (int)$this->request->param('piles_id');
        if ($billId <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($billId);
        if ($info['id'] <= 0) {
            return $this->error('信息不存在');
        }
        return $this->fetch('piles/basic/detail', [
            'info' => $info,
            'orderAddAuth' => property_auth('propertyPilesOrderAdd'),
            'orderEditAuth' => property_auth('propertyPilesOrderEdit'),
            'orderDelAuth' => property_auth('propertyPilesOrderDel'),
            'orderDetailAuth' => property_auth('propertyPilesOrderDetail'),
            'orderRefundAuth' => property_auth('propertyPilesOrderRefund'),
            'codeAddAuth' => property_auth('propertyPilesCodeAdd'),
            'codeEditAuth' => property_auth('propertyPilesCodeEdit'),
            'codeDelAuth' => property_auth('propertyPilesCodeDel'),
            'handleFaultyAuth' => property_auth('propertyPilesFaultyLogHandle'),
            'delFaultyAuth' => property_auth('propertyPilesFaultyLogDel'),
        ]);
    }

    /**
     * 删除充电桩
     * @return string|\think\response\Json|\think\response\View
     *
     * @author Amos
     * 2024-01-30 10:47
     */
    public function del()
    {
        $ids = (array)$this->request->param('ids');
        $remark = $this->request->param('remark', '');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId, $remark);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除充电桩失败', $e);
            return $this->error('网络失败');
        }
    }

    public function pilesLog(PilesLogRepository $logRepository)
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'piles_id' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $logRepository->getList($where, $page, $limit);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
    }

}